import React, {useEffect,useState} from 'react';
import {message, Modal, Skeleton} from "antd";
import ProForm, {ProFormSwitch, ProFormText} from "@ant-design/pro-form";
import {addLink, editLink, getLinkDetail} from "@/services/link";

const AddOrEdit = (props) => {



  const [initialValues,setInitialValues] = useState(undefined)

  const { id, showModal, visible, ref } = props


  // 更新 打开显示模态框 获取链接数据
  useEffect(async () => {
    if (id) {
      const Detail = await getLinkDetail(id)
        setInitialValues(Detail.data)
        console.log(Detail);
    }
  },[id])

  //添加链接的方法
  const addLinkData = async (data) => {
    if (data.id){
      const res = await editLink(data.id,data)
      if (res.status == null){
        message.success("修改成功")
        showModal(false)
        ref.current.reload();
      }else{
        message.error('修改失败')
      }
    }else{
      data.display = data.display ? 1 : 0
      const res = await addLink(data)
      if (res.status == null){
        message.success("添加成功")
        showModal(false)
        ref.current.reload();
      }else{
        message.error('添加失败')
      }
    }

  }



  return (
    <div>
      <Modal
        title={id != undefined ? '修改链接' : '添加链接'}
        visible={visible}
        footer={null}
        destroyOnClose={true}
        onCancel={() => showModal(false)}>
      {
        initialValues == undefined && id != undefined ? <Skeleton active/> :
            <ProForm
              onFinish={(data) => addLinkData(data)}
              initialValues={initialValues}
            >
              <ProFormText
                name="id"
                hidden={true}
              />
              <ProFormText
                label="链接名称"
                name="name"
                rules={[
                  {
                    required: true,
                    message: '请输入链接名称'
                  }
                ]}
              />
              <ProFormText
                label="链接地址"
                name="url"
                rules={[
                  {
                    required: true,
                    message: '请输入链接地址'
                  }
                ]}
              />
              <ProFormSwitch
                label="连接显示状态"
                name="display"
              />
              <ProFormText
                label="链接描述"
                name="describe"
                rules={[
                  {
                    required: true,
                    message: '请输入链接描述'
                  }
                ]}
              />
            </ProForm>
        }
      </Modal>
    </div>
  );
};

export default AddOrEdit;
